<template>
  <div class="login-container">
    <el-card class="login-card">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="验证码登录" name="code">
          <el-form
            :model="codeForm"
            :rules="codeRules"
            ref="codeFormRef"
            class="login-form"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="codeForm.phone"
                placeholder="请输入手机号"
                prefix-icon="el-icon-phone"
              />
            </el-form-item>

            <el-form-item prop="imageCode">
              <el-input
                v-model="codeForm.imageCode"
                placeholder="请输入图片验证码"
                prefix-icon="el-icon-edit"
                :disabled="!uuid"
              />
              <img
                class="image-code"
                :src="imageCodeUrl"
                @click="refreshImageCode"
                alt="图片验证码"
              />
            </el-form-item>

            <el-form-item prop="smsCode">
              <el-input
                v-model="codeForm.smsCode"
                placeholder="请输入短信验证码"
                prefix-icon="el-icon-key"
                :disabled="countdown < 0"
              >
                <template #append>
                  <el-button
                    :disabled="countdown > 0 || !codeForm.phone || !codeForm.imageCode"
                    @click="sendSmsCode"
                  >
                    {{ countdown > 0 ? `${countdown}s后重试` : '获取短信验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="handleCodeLogin"
                class="login-btn"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="密码登录" name="password">
          <el-form
            :model="passwordForm"
            :rules="passwordRules"
            ref="passwordFormRef"
            class="login-form"
          >
            <el-form-item prop="phone">
              <el-input
                v-model="passwordForm.phone"
                placeholder="请输入手机号"
                prefix-icon="el-icon-phone"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="passwordForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="el-icon-lock"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="handlePasswordLogin"
                class="login-btn"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div class="switch-login">
        <span @click="activeTab = 'code'">验证码登录</span>
        <span>|</span>
        <span @click="activeTab = 'password'">密码登录</span>
        <span>|</span>
        <span @click="toRegister">注册</span>
      </div>

      <!-- 第三方登录图标组 -->
      <div class="third-party-icons">
        <!-- 钉钉登录 -->
        <div class="third-party-icon" @click="handleDingTalkLogin">
          <img
            src="https://ts1.tc.mm.bing.net/th/id/R-C.d0b88ed496cd268bb0845f2cc141aa3e?rik=9ZbjdGJJU7TB3g&riu=http%3a%2f%2fwww.kuaipng.com%2fUploads%2fpic%2fw%2f2020%2f06-24%2f86413%2fwater_86413_698_698_.png&ehk=df4WTY2g86komR%2flugk%2b4wzdi%2bCJCAF5D98a6eeDwzU%3d&risl=&pid=ImgRaw&r=0"
            alt="钉钉"
            class="icon-image"
          />
        </div>

        <!-- 微博登录（使用有效图标链接） -->
        <a
          href="https://api.weibo.com/oauth2/authorize?client_id=你的微博APP_ID&redirect_uri=你的微博回调地址"
          class="third-party-icon"
          target="_blank"
        >
          <img
            src="https://img.icons8.com/color/48/000000/weibo.png"
            alt="微博"
            class="icon-image"
          />
        </a>

        <!-- QQ登录（使用有效图标链接） -->
        <a
          href="https://graph.qq.com/oauth2.0/authorize?client_id=你的QQ_APP_ID&redirect_uri=你的QQ回调地址&response_type=code"
          class="third-party-icon"
          target="_blank"
        >
          <img
            src="https://img.icons8.com/color/48/000000/qq.png"
            alt="QQ"
            class="icon-image"
          />
        </a>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

// 状态管理
const activeTab = ref('code');

const countdown = ref(0);
const errorMsg = ref('');
const uuid = ref('');
let initialUuid = '';

// 验证码登录表单
const codeForm = reactive({
  phone: '',
  imageCode: '',
  smsCode: ''
});

// 密码登录表单
const passwordForm = reactive({
  phone: '',
  password: ''
});

// 图片验证码URL
const imageCodeUrl = ref('');

// 表单校验规则
const codeRules = reactive({
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }],
  imageCode: [{ required: true, message: '请输入图片验证码', trigger: 'blur' }],
  smsCode: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }]
});

const passwordRules = reactive({
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
});

// 生命周期钩子：初始化图片验证码
onMounted(() => {
  generateInitialUuid();
  refreshImageCode();
});

// 生成唯一且固定的 UUID（仅在初始化时生成一次）
const generateInitialUuid = () => {
  const chars = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
  initialUuid = chars.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
  uuid.value = initialUuid; // 仅在生成完成后赋值一次
};
//跳转注册页面
const toRegister = () => {
  router.push('/register')
}
// 刷新图片验证码
const refreshImageCode = () => {
  imageCodeUrl.value = `http://127.0.0.1:8000/users/imagecode/?uuid=${uuid.value}&t=${Date.now()}`;
};

// 发送短信验证码
const sendSmsCode = async () => {
  try {
    const { data } = await axios.post('http://127.0.0.1:8000/users/send_code/', {
      phone: codeForm.phone,
      imagecode: codeForm.imageCode,
      uuid: uuid.value
    });

    if (data.code === 200) {
      ElMessage.success('短信验证码发送成功');
      startCountdown();
    } else {
      ElMessage.error(data.msg);
      refreshImageCode(); // 错误后刷新图片验证码
    }
  } catch (error) {
    ElMessage.error('发送验证码失败，请重试');
    console.error(error);
  }
};

// 倒计时逻辑
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    if (countdown.value < 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};

// 验证码登录
const handleCodeLogin = async () => {
  try {
    const { data } = await axios.post('http://127.0.0.1:8000/users/code_login/', {
      phone: codeForm.phone,
      code: codeForm.smsCode
    });

    if (data.code === 200) {
      ElMessage.success('登录成功');
      // 存储Token到本地存储
      localStorage.setItem('token', `Bearer ${data.token}`);
      localStorage.setItem('userid', data.userid);
      localStorage.setItem('refreshToken', data.retoken);
      // 跳转到个人中心页面
      router.push('/profile');
    } else {
      ElMessage.error(data.msg);
      router.push('/register');
    }
  } catch (error) {
    ElMessage.error('登录失败，请检查手机号和验证码');
    console.error(error);
  }
};

// 密码登录
const handlePasswordLogin = async () => {
  try {
    const { data } = await axios.post('http://127.0.0.1:8000/users/password_login/', {
      phone: passwordForm.phone,
      password: passwordForm.password
    });

    if (data.code === 200) {
      ElMessage.success('登录成功');
      // 存储Token到本地存储
      localStorage.setItem('token', `Bearer ${data.token}`);
      localStorage.setItem('userid', data.userid);
      localStorage.setItem('refreshToken', data.retoken);
      // 跳转到个人中心页面
      router.push('/profile');
    } else {
      ElMessage.error(data.msg);
      router.push('/register');
    }
  } catch (error) {
    ElMessage.error('登录失败，请检查手机号和密码');
    console.error(error);
  }
};

// 钉钉登录相关
const handleDingTalkLogin = () => {
  // 生成随机state防止CSRF攻击
  const state = Math.random().toString(36).substr(2);
  localStorage.setItem('dingtalk_state', state);
  
  // 构建钉钉登录URL
  const dingTalkUrl = new URL('https://login.dingtalk.com/oauth2/auth');
  dingTalkUrl.searchParams.append('response_type', 'code');
  dingTalkUrl.searchParams.append('client_id', 'dingtvk3mg5whlxuhdim');
  dingTalkUrl.searchParams.append('scope', 'openid');
  dingTalkUrl.searchParams.append('state', state);
  dingTalkUrl.searchParams.append('prompt', 'consent');
  dingTalkUrl.searchParams.append('redirect_uri', 'http://127.0.0.1:8000/users/dingtalk/callback/');
  
  // 跳转到钉钉登录页面
  window.location.href = dingTalkUrl.toString();
};

// 监听路由变化，处理钉钉回调
watch(
  () => route.query,
  (query) => {
    // 处理后端重定向回来的登录信息
    if (query.token && query.userid && query.retoken) {
      // 存储登录信息，确保token带有Bearer前缀
      const token = query.token.startsWith('Bearer ') ? query.token : `Bearer ${query.token}`;
      localStorage.setItem('token', token);
      localStorage.setItem('userid', query.userid);
      localStorage.setItem('refreshToken', query.retoken);
      
      ElMessage.success('钉钉登录成功');
      router.push('/profile'); // 跳转到个人中心页面
    }
  },
  { immediate: true }
);

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
  padding: 30px;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-form {
  width: 100%;
}

.el-input {
  margin-bottom: 15px;
}

.image-code {
  width: 120px;
  height: 40px;
  margin-left: 10px;
  vertical-align: middle;
  cursor: pointer;
}

.login-btn {
  width: 100%;
  margin-top: 20px;
}

.switch-login {
  margin-top: 20px;
  text-align: center;
  color: #666;
}

.switch-login span {
  cursor: pointer;
  margin: 0 10px;
}

/* 第三方登录样式 */
.third-party-title {
  margin: 20px 0 15px;
}

.third-party-icons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 20px 0;
}

.third-party-icon {
  cursor: pointer;
  display: inline-block;
  width: 48px;
  height: 48px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
  text-decoration: none;
}

.third-party-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.icon-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 适配不同屏幕尺寸 */
@media (max-width: 768px) {
  .third-party-icons {
    gap: 15px;
    flex-wrap: wrap;
  }

  .third-party-icon {
    width: 40px;
    height: 40px;
  }
}
</style>